###
	Outline
	
	- Global Vars
	- Core Code (run once)
		-- add table / form
		-- self subscription (duplicate check)
		-- main subscription (fill form)
	- Event Handlers
		-- cancel button
		-- submit button
			-- check duplicate
			-- check invalid fields
			-- doc obj and parse
			-- save doc to couch
				-- publish Donor ID
###

define [
	'jquery'
	'template'
	'lib/jquery.couch.js'
	'helper'
], ($, undef, undef, H) ->
	S = {}

	# Custom Date() helper function to output ISODate Format (YYYY-MM-DD HH:MM:SS)
	Date.prototype.isoDateTime = () ->
		if @getUTCMonth()+1 < 10 then _month = "0#{@getUTCMonth() + 1}" else _month = @getUTCMonth() + 1
		if @getUTCDate() < 10 then _date = "0#{@getUTCDate()}" else _date = @getUTCDate()
		return "#{@getUTCFullYear()}-#{_month}-#{_date} #{(s = @toTimeString().split('GMT')[0]).slice(0, s.length - 1)}"

	$.fn.mb_add_donation = (SamCtx) ->

		# --- Global Variables and Function ---------------
			$this = $(ins = @)
			_time = _dID = savedAmount = ""
			S = SamCtx
			$tbody = $this.find('tbody')

		# --- Core code of plugin -------------------------

			unless @mb_plugin()
				@mb_plugin 'add_donation'

				# Self-subscription of donation ID to retrieve "last-created" donation doc date so that
				# subsequent matching of date can be tested to avoid duplicate donation creation
				$.subscribe "mb.donation", (e, arg) => 
					H.db().openDoc arg['id'],
						{success: (doc) -> _time = doc.donation_date if arg['ok']}

				# Main subscription event to handle a donor_id being published from donor_detail
				$.subscribe "mb.add_donation", (e, arg) => 
					_dID = arg['donor_id']

					# Clone a copy of the saved tbody form
					$form = $tbody.clone()
					# Remove elements based on "ind" or "org" classes
					$form.find(".field:not(#{arg['class1']})").remove()
					# Remove secondary elements if in "ind" class, class2 is either ".all" or ".family"
					$form.find(".field.ind:not(.all)").remove() if arg['class2'] is ".all"
					# Add this form to our table
					$("table", @).empty().append($form)

					# Empty all manually input fields to empty form
					$('[name="login_id1"], [name="comment"]', @).val("")
					# Display subscribed donor ID
					$('[name="donor_id"]', @).val(_dID)

					# Refresh button updates the time 
					$('#refresh', @).click () ->
						$('[name="donation_date"]').val(d = ((new Date()).isoDateTime())).html(d)
					# Invoke a click on the refresh button to fill out the Donation Date field
					$('#refresh', @).click()

					$('[name="donation_amount"]', @).val(arg['amount'])


		# --- Button Event Handlers ------------------

			$('table', @).on 'focus', '[name="donation_amount"]', ->
				savedAmount = $(@).val()
				$(@).val $(@).val().replace(/[$]|\.00/g, "")

			$('table', @).on 'blur', '[name="donation_amount"]', ->
				# Helper error handling when field is invalidated
				# When invalidation occurs, the textbox is formatted to last saved appropriate value
				# and the textbox is selected so user will have to input something valid
				err = (msg, $this)->
					$this.val(savedAmount).select()
					$.publish "mb.msg", 
						msg: msg
						type: "error"

				# Keep a copy of the current value
				$old_val = $(@).val()

				# Don't do anything if the current value is blank
				if $old_val is ""
					err("Donation Amount cannot be empty", $(@))
					return false
				# Error checking
				if $old_val.indexOf(".") isnt -1
					if $old_val.split(".").length > 2 or $old_val.split(".")[1] isnt "00"
						err("Donation amount is not valid.", $(@))
						return false
				if isNaN($old_val) or $old_val < 0
					err("Donation amount is not a number.", $(@))
					return false

				# Error check passed, remove $ signs and ".00" if user manually input into the 
				# field, then appened $ and ".00" automatically
				$(@).val "$#{$(@).val().replace(/[$]|\.00/g, '')}.00"
				return

			# Handle Cancel button click
			$('input:button[value="Cancel"]', @).on 'click', -> S.setLocation "#/donor_detail"

			# Handle Submit button click
			$('input:button[value="Submit"]', @).on 'click', ->

				# Check to see for duplicate creation
				if _time isnt ""
					if $("[name='donation_date']").val().toString() is _time.toString()
						$.publish "mb.msg", 
							msg: "Duplicate donation. Refresh Payment Date field to add new donation."
							type: "error"
						return false

				# Check to see for empty Donation Amount field
				if $('input[name="donation_amount"]').val().length is 0
					$.publish "mb.msg",
						msg: "Donation amount field cannot be empty."
						type: "error"
					return false

				$('[name="donation_amount"]').select()

				# Create helper doc object and parse the serializeArray of the form
				(doc = new H.doc).parse $('form', ins).serializeArray()
				doc.cash or= false

				# Save object to couch document
				H.db().saveDoc doc,
					{success: (save)->

						# Publish donation detail (ie. ID) for donation_detail is subscribed to
						$.publish "mb.donation", save

						$('[name="donation_amount"]', ins).blur()

						# Publish to "mb.donor" to let view_receipt know that it should refresh its 
						# record table only when donation has been added successfully
						if save.ok
							$.publish "mb.donor", {donor_id: _dID} 
							S.setLocation "#/donation_detail"
					}
				return false
		return @
	return
